const Router      = require('koa-router'),
      UserService = require('../service/user.service');

const router = new Router({
    prefix: '/users'
});

router.get('/',
    function *(next) {
        this.users = yield UserService.findAll();
        yield next;
    },
    function *() {
        this.body = this.users;
    });

router.post('/save',
    function *() {
        let query = yield UserService.create(this.request.body);
        this.body = Result.success('添加成功', query.insertId);
    });

router.get('/:id(\\d+)',
    function *(next) {
        this.user = yield UserService.findOne(this.params.id);
        yield next;
    },
    function *() {
        this.body = this.user;
    });

router.delete('/:id(\\d+)/remove',
    function *() {
        yield UserService.remove(this.params.id);
        this.body = Result.success('删除成功');
    });

router.put('/:id(\\d+)/update',
    function *() {
        let user = this.request.body;
        user.id = this.params.id;
        yield UserService.update(user);
        this.body = Result.success('修改成功');
    });

module.exports = router;